package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.ProjectScience;
import cn.stylefeng.guns.modular.business.entity.SubDic;
import cn.stylefeng.guns.modular.business.enums.ProjectScienceExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.ProjectScienceMapper;
import cn.stylefeng.guns.modular.business.pojo.ProjectScienceRequest;
import cn.stylefeng.guns.modular.business.service.ProjectScienceService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工程科技业务实现层
 *
 * @author zhangyaowen
 * @date 2021/10/12 15:07
 */
@Service
public class ProjectScienceServiceImpl extends ServiceImpl<ProjectScienceMapper, ProjectScience> implements ProjectScienceService {

    @Resource
    private LoginUserApi loginUserApi;
    @Resource
    private SubUseBrowseService subUseBrowseService;

	@Override
    public void add(ProjectScienceRequest projectScienceRequest) {
        ProjectScience projectScience = new ProjectScience();
        BeanUtil.copyProperties(projectScienceRequest, projectScience);
        this.save(projectScience);
    }

    @Override
    public void del(ProjectScienceRequest projectScienceRequest) {
        ProjectScience projectScience = this.queryProjectScience(projectScienceRequest);
        this.removeById(projectScience.getId());
    }

    @Override
    public void edit(ProjectScienceRequest projectScienceRequest) {
        ProjectScience projectScience = this.queryProjectScience(projectScienceRequest);
        BeanUtil.copyProperties(projectScienceRequest, projectScience);
        this.updateById(projectScience);
    }

    @Override
    public ProjectScience detail(ProjectScienceRequest projectScienceRequest) {
        return this.queryProjectScience(projectScienceRequest);
    }

    @Override
    public PageResult<Map<String, Object>> findPage(String value,String river,String project) {
        String[] rivers = {};
        String[] projects ={};
        if(!river.equals("") ) {
            rivers = StrUtil.splitToArray(river, ";");
        }
        if(!project.equals("")) {
            projects = StrUtil.splitToArray(project, ";");
        }
        LambdaQueryWrapper<ProjectScience> wrapper = createWrapperes(rivers,projects,value);
        Page<ProjectScience> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);

        PageResult<ProjectScience> projectSciencePageResult =  PageResultFactory.createPageResult(sysRolePage);
        List<ProjectScience> list = projectSciencePageResult.getRows();
        PageResult<Map<String, Object>> pageResult = new PageResult<>();
        List<Map<String,Object>> mapList = new ArrayList<>();
        for(ProjectScience projectScience : list){
            Map<String, Object> map = new HashMap<String, Object>();
//            map = JSONObject.parseObject(JSONObject.toJSONString(projectScience), Map.class);
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
            String jmid = YunHeKey.GCKJ+projectScience.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            map.put("title",projectScience.getPsTitle());
            map.put("historyDating",projectScience.getHistoryDating());
            map.put("annalsfrom",projectScience.getPsAnnalsfrom());
            mapList.add(map);
        }
        pageResult.setRows(mapList);
        pageResult.setPageNo(projectSciencePageResult.getPageNo());
        pageResult.setTotalRows(projectSciencePageResult.getTotalRows());
        pageResult.setPageSize(projectSciencePageResult.getPageSize());
        pageResult.setTotalPage(projectSciencePageResult.getTotalPage());
        return pageResult;
    }

    @Override
    public List<Map<String,Object>> findChoose() {
        LambdaQueryWrapper<ProjectScience> queryWrapper = new LambdaQueryWrapper<>();
        List<Map<String,Object>> List = new ArrayList<>();
        List<Map<String,Object>> mapList = new ArrayList<>();
        List<Map<String,Object>> mapList1 = new ArrayList<>();
        List<Map<String,Object>> findList = new ArrayList<>();
        Map<String, Object> findProject = new HashMap<String, Object>();
        Map<String, Object> findRiver = new HashMap<String, Object>();
        List<ProjectScience> list= this.list(queryWrapper);

        // 根据RiverName去重
        //1.提取出list对象中的一个属性
//        List<String> riverList1 = list.stream().map(ProjectScience::getRiverName).collect(Collectors.toList());

        //2.提取出list对象中的一个属性并去重
        List<String> riverList2 = list.stream().map(ProjectScience::getRiverName).distinct().collect(Collectors.toList());
        // 根据PsFirst去重
        //1.提取出list对象中的一个属性
//        List<String> projectList1 = list.stream().map(ProjectScience::getPsFirst).collect(Collectors.toList());

        //2.提取出list对象中的一个属性并去重
        List<String> projectList2 = list.stream().map(ProjectScience::getPsFirst).distinct().collect(Collectors.toList());
        for(String ss : riverList2){
            Map<String, Object> map = new HashMap<String, Object>();
            if("".equals(ss) || ss == null){
                continue;
            }else{
                map.put("river",ss);
                mapList.add(map);
            }

        }
        for(String sss : projectList2){
            Map<String, Object> map1 = new HashMap<String, Object>();
            if("".equals(sss) || sss == null){
               continue;
            }else{
                map1.put("project", sss);
                mapList1.add(map1);
            }
        }

        findProject.put("list",mapList);
        findProject.put("title","关键工程");
        findRiver.put("list",mapList1);
        findRiver.put("title","河道分布");
        findList.add(findRiver);
        findList.add(findProject);
        return findList;
    }




    @Override
    public List<ProjectScience> findList(ProjectScienceRequest projectScienceRequest) {
        LambdaQueryWrapper<ProjectScience> wrapper = this.createWrapper(projectScienceRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/10/12 15:07
     */
    private ProjectScience queryProjectScience(ProjectScienceRequest projectScienceRequest) {
        ProjectScience projectScience = this.getById(projectScienceRequest.getId());
        if (ObjectUtil.isEmpty(projectScience)) {
            throw new ServiceException(ProjectScienceExceptionEnum.PROJECTSCIENCE_NOT_EXISTED);
        }
        return projectScience;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/10/12 15:07
     */
    private LambdaQueryWrapper<ProjectScience> createWrapper(ProjectScienceRequest projectScienceRequest) {
        LambdaQueryWrapper<ProjectScience> queryWrapper = new LambdaQueryWrapper<>();

        Long id = projectScienceRequest.getId();
        String riverName = projectScienceRequest.getRiverName();
        String psFirst = projectScienceRequest.getPsFirst();
        String psSecond = projectScienceRequest.getPsSecond();
        String psThrid = projectScienceRequest.getPsThrid();
        String historyDating = projectScienceRequest.getHistoryDating();
        String theCommon = projectScienceRequest.getTheCommon();
        String keyProject = projectScienceRequest.getKeyProject();
        String quoteAnnotation = projectScienceRequest.getQuoteAnnotation();
        String psAnnalsfrom = projectScienceRequest.getPsAnnalsfrom();
        String psAnnalspage = projectScienceRequest.getPsAnnalspage();

        queryWrapper.eq(ObjectUtil.isNotNull(id), ProjectScience::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(riverName), ProjectScience::getRiverName, riverName);
        queryWrapper.like(ObjectUtil.isNotEmpty(psFirst), ProjectScience::getPsFirst, psFirst);
        queryWrapper.like(ObjectUtil.isNotEmpty(psSecond), ProjectScience::getPsSecond, psSecond);
        queryWrapper.like(ObjectUtil.isNotEmpty(psThrid), ProjectScience::getPsThrid, psThrid);
        queryWrapper.like(ObjectUtil.isNotEmpty(historyDating), ProjectScience::getHistoryDating, historyDating);
        queryWrapper.like(ObjectUtil.isNotEmpty(theCommon), ProjectScience::getTheCommon, theCommon);
        queryWrapper.like(ObjectUtil.isNotEmpty(keyProject), ProjectScience::getKeyProject, keyProject);
        queryWrapper.like(ObjectUtil.isNotEmpty(quoteAnnotation), ProjectScience::getQuoteAnnotation, quoteAnnotation);
        queryWrapper.like(ObjectUtil.isNotEmpty(psAnnalsfrom), ProjectScience::getPsAnnalsfrom, psAnnalsfrom);
        queryWrapper.like(ObjectUtil.isNotEmpty(psAnnalspage), ProjectScience::getPsAnnalspage, psAnnalspage);

        return queryWrapper;
    }
    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/30 10:17
     */
    private LambdaQueryWrapper<ProjectScience> createWrapperes( String[] rivers, String[] projects, String value) {
        LambdaQueryWrapper<ProjectScience> queryWrapper = new LambdaQueryWrapper<ProjectScience>();
        queryWrapper.and(i-> i.like(ObjectUtil.isNotNull(value), ProjectScience::getPsTitle, value).or()
                .like(ObjectUtil.isNotNull(value), ProjectScience::getRiverName, value).or()
                .like(ObjectUtil.isNotNull(value), ProjectScience::getHistoryDating, value).or()
                .like(ObjectUtil.isNotNull(value), ProjectScience::getPsAnnalsfrom, value));
        if( rivers.length !=0 ) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < rivers.length; i++) {
                    String time = rivers[i];
                    wrapper.like(ObjectUtil.isNotEmpty(time), ProjectScience::getRiverName, time);
                    if (i != rivers.length - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        if( projects.length !=0 ) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < projects.length; i++) {
                    String time = projects[i];
                    wrapper.like(ObjectUtil.isNotEmpty(time), ProjectScience::getPsFirst, time);
                    if (i != projects.length - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        return queryWrapper.orderByDesc(ProjectScience::getHistoryDating);
    }


    @Override
    public List<Map<String, Object>> toReview(String jmId) {
        byte[] key =YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(jmId, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YHSJ后面真实的的id
        String id = StrUtil.subAfter(decryptStr,YunHeKey.GCKJ,false);
        HttpServletRequest request = HttpServletUtil.getRequest();
        Long userid;
        if (ObjectUtil.isNotNull(request)) {

            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();
        } else {
            throw new ServiceException(ProjectScienceExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<ProjectScience> queryWrapper = new LambdaQueryWrapper<>();
        if ("".equals(id)) {
            List<Map<String, Object>> mapLists = new ArrayList<>();
//            Map<String, Object> map =new HashMap<>();
//            map.put("error","id为空");
            return mapLists;
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), ProjectScience::getId, id);
        List<ProjectScience> projectScienceList = this.list(queryWrapper);
        if(userid != 0l && userid != -1l) {
            subUseBrowseService.saveBrowse(YunHeKey.GONGCHENGKJ,projectScienceList.get(0).getPsTitle(),userid,request);
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (ProjectScience projectScience : projectScienceList) {

            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(projectScience), Map.class);

            // 获取类的属性
            Field[] declaredFields = ProjectScience.class.getDeclaredFields();
            List<Map<String, Object>> mplist = new ArrayList<>();
            // 遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
            if (declaredFields.length != 0) {

                int i = 1;
                Map<String, Object> p = new HashMap<String, Object>();
                for (Field field : declaredFields) {

                    Map<String, Object> mp = new HashMap<String, Object>();
                    if (field.getAnnotation(ApiModelProperty.class) != null) {
                        //获取注解属性
                        ApiModelProperty aa = field.getAnnotation(ApiModelProperty.class);
                        // key和value可根据需求存
                        // 这存的key为注解的值，value为类属性名
                        if ("psTitle".equals(field.getName()) || "keyProject".equals(field.getName())) {

                            if("keyProject".equals(field.getName()) ) {
                                p.put(field.getName(), map.get(field.getName()));
                            }else{
                                p.put("title", map.get(field.getName()));
                            }
                        }else{
                            mp.put("key", aa.value());
                            mp.put("value", map.get(field.getName()));

                            if (i != 1) {
                                mplist.add(mp);
                            }
                        }

                    }
                    i++;
                }
//                title = StrUtil.sub(title,0,title.length()-1);

                p.put("list", mplist);
                if (i != 1) {
                    mapList.add(p);
                }
            }
        }
        return mapList;
    }


    public List<Map<String,Object>> findAllList(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<ProjectScience> wrapper = createWrappers(riverList,townList,times,name);
        List<ProjectScience>  list = this.list(wrapper);
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(ProjectScience projectScience:list) {
            Map<String, Object> map = new HashMap<String, Object>();
//            Map<String, Object> map1 = new HashMap<String, Object>();
//            map = JSONObject.parseObject(JSONObject.toJSONString(eventsInfo), Map.class);
            String titleOne =projectScience.getPsTitle();

            map.put("title", titleOne);
            map.put("historyDating",projectScience.getHistoryDating());
            map.put("theCommon",projectScience.getTheCommon());
            map.put("from",projectScience.getPsAnnalsfrom() );
            map.put("createTime",DateUtil.format(projectScience.getCreateTime(), "yyyy-MM-dd"));
            map.put("type",YunHeKey.GCKJ);
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.GCKJ+projectScience.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            mapList.add(map);
        }
        return mapList;
    }
    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/30 10:17
     */
    private LambdaQueryWrapper<ProjectScience> createWrappers(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<ProjectScience> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.and(i-> i.like(ObjectUtil.isNotNull(name), ProjectScience::getRiverName, name).or()
                .like(ObjectUtil.isNotNull(name), ProjectScience::getHistoryDating, name).or()
                .like(ObjectUtil.isNotNull(name), ProjectScience::getPsAnnalsfrom, name).or()
                .like(ObjectUtil.isNotNull(name), ProjectScience::getPsFirst, name));
        if( !riverList.isEmpty()) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < riverList.size(); i++) {
                    String dicAname = riverList.get(i).getDicAname();
                    wrapper.like(ObjectUtil.isNotEmpty(dicAname), ProjectScience::getRiverName, dicAname);
                    if (i != riverList.size() - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        if( times.length !=0) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < times.length; i++) {
                    String time = times[i];
                    wrapper.like(ObjectUtil.isNotEmpty(time), ProjectScience::getHistoryDating, time);
                    if (i != times.length - 1) {
                        wrapper.or();
                    }
                }
            });
        }
//        for(int i=0 ;i<townList.size();i++) {
//            String dicZname = townList.get(i).getDicZname();
//            String dicAname = townList.get(i).getDicAname();
//            queryWrapper.like(ObjectUtil.isNotEmpty(dicZname), EventsInfo::getEventsPlace, dicZname);
//            queryWrapper.or();
//            queryWrapper.like(ObjectUtil.isNotEmpty(dicAname), EventsInfo::getEventsPlace, dicAname);
//            if(i !=townList.size()-1) {
//                queryWrapper.or();
//            }
//        }
//        for(int i=0 ;i<times.length;i++) {
//            String time = times[i];
//            queryWrapper.like(ObjectUtil.isNotEmpty(time), EventsInfo::getEventsSecond, time);
//            if(i !=times.length-1) {
//                queryWrapper.or();
//            }
//        }
        return queryWrapper;
    }
}